<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form batch-wrap">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="100px"
            id="form"
          >
            <el-form-item label="" prop="date_type" class="wid100 methods">
              <el-select v-model="form.date_type" placeholder="请选择">
                <el-option label="配送日期" value="1"> </el-option>
                <el-option label="下单日期" value="2"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="establishTime" class="time_item">
              <el-date-picker
                v-model="establishTime"
                type="daterange"
                class="time220 marginLeft5s"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
                @change="dateChange"
              />
            </el-form-item>
            <el-form-item label="支付方式：" prop="is_piroment">
              <el-select
                v-model.trim="form.is_piroment"
                placeholder="支付方式"
                class="wid220"
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(is_piroment, index) in is_piroment"
                  :key="index"
                  :label="is_piroment"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
              <el-button class="mg-r-6" @click="summaryExport">汇总导出</el-button>
              <el-button @click="exportform">导出</el-button>
            </MainFormBtn>
          </el-form>
        </div>
        <div class="main_table mg-t-6">
          <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          fit
          highlight-current-row
          :header-cell-style="tableHeightStyle"
          :header-cell-class-name="this.$verticaline"
          :height="borderHeight"
        >
          <el-table-column label="配送日期" prop="day_time">
            <template slot="header">
              <headerSortArrow
                label="day_time"
                ref="arrow1"
                @handleSort="handleSort($event, 'arrow1')"
                >配送日期</headerSortArrow
              >
            </template>
            <template slot-scope="scope">{{
              parseTime(scope.row.day_time, "{y}-{m}-{d}")
            }}</template>
          </el-table-column>
          <el-table-column label="平均订单价" prop="avg_money">
            <template slot-scope="scope">{{
              scope.row.avg_money | twoPlace
            }}</template>
          </el-table-column>
          <el-table-column label="平均客单价" prop="avg_company_money">
            <template slot-scope="scope">{{
              scope.row.avg_company_money | twoPlace
            }}</template>
          </el-table-column>
          <el-table-column label="下单金额" prop="order_money">
            <template slot-scope="scope">{{
              scope.row.order_money | twoPlace
            }}</template>
          </el-table-column>
          <el-table-column label="订单数量" prop="order_num">
            <template slot-scope="scope">{{ scope.row.order_num }}</template>
          </el-table-column>
          <el-table-column label="退单数量" prop="return_num" />
          <el-table-column label="配送金额" prop="send_money">
            <template slot="header">
              <headerSortArrow
                label="send_money"
                ref="arrow2"
                @handleSort="handleSort($event, 'arrow2')"
                >配送金额</headerSortArrow
              >
            </template>
            <template slot-scope="scope">{{
              scope.row.send_money | twoPlace
            }}</template>
          </el-table-column>
          <el-table-column label="退货金额" prop="return_money">
            <template slot="header">
              <headerSortArrow
                label="return_money"
                ref="arrow3"
                @handleSort="handleSort($event, 'arrow3')"
                >退货金额</headerSortArrow
              >
            </template>
          </el-table-column>
          <el-table-column
            label="实配送金额"
            prop="send_real_money"
          ></el-table-column>
          <el-table-column label="管理操作" prop="" fixed="right">
            <template slot-scope="scope">
              <el-link type="primary" @click="jump(scope.row)"> 明细 </el-link>
            </template>
          </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="汇总导出"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="close"
    >
      <el-form :model="formInline" class="demo-form-inline" label-width="120px">
        <el-form-item label="订单日期：">
          <el-date-picker
            style="width: 220px"
            v-model="formInline.order_dates"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dialogDateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户：">
          <change-user-input
            ref="changeUserInput"
            @sendValue="getUser"
            @clear="clearUid"
            @change="getArticleList"
          ></change-user-input>
        </el-form-item>
        <!-- <el-form-item label="订单状态">
          <el-select v-model="status" placeholder="请选择">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="dialogexportsale">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  get_saleOrder,
  export_exportSaleOrder,
  export_exportOrderDetail,
  get_report_base,
} from "@/api/report/index";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { report_shortcuts } from "@/options/new_dateOption";
import { parseTime, getNowMonth, exportMethod } from "@/utils/index";
import headerSortArrow from "@/views/report/components/headerSortArrow";
import { debounce } from "@/utils/debounce";
export default {
  mixins: [mixins],
  components: { headerSortArrow },
  data() {
    return {
      // 汇总导出的展示与隐藏
      dialogVisible: false,
      formInline: {
        order_date: "",
        order_dates: null,
        user_id: "",
      },

      pickerOptions: report_shortcuts,
      exportMethod,
      // 时间
      parseTime,
      getNowMonth,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: [],
      listLoading: false,
      // 搜索
      form: {
        start_time: "",
        end_time: "",
        is_piroment: "",
        date_type: "1",
        order_by: "",
        order_type: "", //1升序  2降序
      },
      is_piroment: {},
      establishTime: [],
      moredata: false,
    };
  },
  filters: {
    twoPlace(value) {
      let decimals = 2;
      var _sign = value < 0 ? -1 : 1;
      return Number(
        `${Math.round(`${value * _sign}e${decimals}`)}e-${decimals}` * _sign
      ).toFixed(2);
    },
  },
  created() {
    this.getNumerical(235);
    this.establishTime = this.getNowMonth();
    this.get_report_base();
    this.get_saleOrder();
  },
  methods: {
    dialogDateChange(e) {
      let start = new Date(e[0]).getTime();
      let end = new Date(e[1]).getTime();
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
        this.$message.warning("选择时间跨度不能超过两个月");
        this.formInline.order_dates = this.getNowMonth()
      }
    },
    startGetting() {
      this.getArticleList();
    },
    // 基本信息
    get_report_base() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      get_report_base(data).then((res) => {
        if (res.errcode == 0) {
          this.is_piroment = res.data.is_piroment;
        }
      });
    },
    get_saleOrder() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      get_saleOrder(data).then((res) => {
        if (res.errcode == 0) {
          this.list = res.data.list;
          this.totalCount = res.data.total;
        } else {
          this.$message.error(res.errmsg);
        }
        this.listLoading = false;
      });
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.establishTime = this.getNowMonth();
      this.getArticleList();
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.get_saleOrder();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.get_saleOrder();
    },
    changePage(page) {
      this.current.page = page;
      this.get_saleOrder();
    },

    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.establishTime[0] ? this.establishTime[0] : "";
      form.end_time = this.establishTime[1] ? this.establishTime[1] : "";
      return form;
    },
    // 导出
    exportform() {
      let start = new Date(this.list_form().start_time).getTime();
      let end = new Date(this.list_form().end_time).getTime();
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
        this.$message.warning("选择时间跨度不能超过两个月");
        this.establishTime = this.getNowMonth();
      } else {
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          this.list_form()
        );
        const notify = this.$notify.info({
          title: "开始导出...",
          type: "success",
          duration: 0,
        });
        export_exportSaleOrder(data).then((res) => {
          this.exportMethod(res, "销售报表-日报表", notify);
        });
      }
    },
    dateChange(val) {
      let start = new Date(val[0]).getTime();
      let end = new Date(val[1]).getTime();
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 365) {
        this.$message.warning("选择时间跨度不能超过一年");
        this.establishTime = this.getNowMonth();
      }
      this.get_saleOrder();
    },

    //页面跳转
    jump(row) {
      let time = row.day_time;
      this.$router.push({
        name: "order_list",
        params: {
          time: time,
          is_piroment: this.form.is_piroment,
        },
      });
    },
    // 排序
    handleSort(data, ref) {
      let arr = ["arrow1", "arrow2", "arrow3"].filter((e) => e != ref);
      arr.map((e) => {
        this.$refs[e].selected = false;
      });
      this.form.order_by = data.label;
      this.form.order_type = data.type;
      this.get_saleOrder();
    },

    // 汇总导出
    summaryExport() {
      this.dialogVisible = true;
    },

    // 获取用户
    getUser(data) {
      let uid = data.info.user_id;
      this.formInline.user_id = uid;
    },
    // 清除用户的uid
    clearUid() {
      this.formInline.user_id = "";
    },
    dialogexportsale: debounce(function () {
      if (this.formInline.order_dates.length == 0) {
        this.$message.error("请选择时间");
        return;
      }
      this.formInline.order_date = this.formInline.order_dates.join("_");
      let data = this._.cloneDeep(this.formInline);
      delete data.order_dates;
      let query = this.packageApi(data);
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_exportOrderDetail(query).then((res) => {
        this.exportMethod(res, "销售报表-汇总明细", notify);
        setTimeout(() => {
          notify.close();
        }, 2000);
      });
    }, 1000),
    close() {
      this.formInline.order_date = "";
      this.$set(this.formInline, "order_dates", []);
      this.formInline.user_id = "";
      this.$refs["changeUserInput"].name = "";
      this.dialogVisible = false;
    },

    // 封装请求的sign和timeStamp字段
    packageApi(data = {}) {
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
      return query;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 300px);
  }
}

// 支付状态
.success {
  color: $green;
}
.unpaid {
  color: $colour_red;
}
// 订单状态
.order0 {
  color: $order_color1;
}
.order1 {
  color: $order_color2;
}
.order2 {
  color: $order_color3;
}
.order4 {
  color: $order_color4;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}

.wid100 {
  width: 100px;
}

.marginLeft5s {
  margin-left: -5px;
}
/deep/.methods .el-input__inner {
  border: none;
}

.reset {
  background: none;
  color: #03a98e;
}
</style>
